package org.wendu.wdoa.security.role.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wendu.wdoa.common.ex.BusinessException;
import org.wendu.wdoa.common.page.PageUtils;
import org.wendu.wdoa.security.home.model.Fun;
import org.wendu.wdoa.security.role.dao.RoleDao;
import org.wendu.wdoa.security.role.dto.FunDto;
import org.wendu.wdoa.security.role.dto.RoleQueryDto;
import org.wendu.wdoa.security.role.service.RoleService;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional // 事务
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public Map<String, Object> getRolePage(RoleQueryDto dto) {
        return PageUtils.getPage(dto, () -> roleDao.findRolePage(dto));
    }

    @Override
    public List<FunDto> getFunList() {
        List<Fun> list = roleDao.findFunList();

        List<FunDto> mainList = new ArrayList<>(); // 主菜单集合
        FunDto currentMain = null;

        for (Fun fun : list) {
            if (currentMain == null || !currentMain.getMenuId().equals(fun.getP_id())) {

                currentMain = new FunDto();
                currentMain.setMenuId(fun.getP_id());
                currentMain.setMenuName(fun.getP_name());
                currentMain.setChildren(new ArrayList<FunDto>());

                mainList.add(currentMain);
            }

            FunDto sub = new FunDto();
            sub.setMenuId(fun.getF_id());
            sub.setMenuName(fun.getF_name());

            currentMain.getChildren().add(sub);
        }
        return mainList;
    }

    @Override
    public void addRole(RoleQueryDto roleQueryDto) {
        String newId = roleDao.findNewId();
        roleQueryDto.setRo_id(newId);
        roleDao.addRole(roleQueryDto);
    }

    @Override
    public List<Integer> getRoleFunIds(String ro_id) {
        return roleDao.findRoleFunIds(ro_id);
    }

    @Override
    public void confirmRoleFuns(String ro_id, Integer[] f_ids) {
        roleDao.deleteRoleFuns(ro_id); // 删除指定角色的所有权限
        if (f_ids == null || f_ids.length == 0) {
            return;
        }
        roleDao.insertRoleFuns(ro_id, f_ids);
    }

    @Override
    public void deleteRoId(Integer ro_id) {
        boolean existsUser = roleDao.findExistsUser(ro_id);
        boolean existFun = roleDao.findExistFun(ro_id);
        if (existsUser){
            throw new BusinessException("存在用户，删除失败");
        }
        else if (existFun){
            throw new BusinessException("存在功能，删除失败");
        }
        roleDao.deleteRoleName(ro_id);
    }

}
